package server.command;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import util.Command;
import util.Constant;
import util.Control;
import util.Statistically;

public class Get extends Command {	
	
	private Statistically rates = new Statistically();
	
	public Get(){super();}
	
	private void sendControlMessenger (Control msg) throws IOException{
		DataOutputStream data_out = new DataOutputStream(getSocket().getOutputStream());
		data_out.flush();
		data_out.writeInt(msg.Code());		
	}
	
	private void sendFile() throws IOException{
		long timeStarted = System.currentTimeMillis();
		OutputStream out = getSocket().getOutputStream();
		DataOutputStream data_out = new DataOutputStream(out);
		DataInputStream data_in = new DataInputStream(getSocket().getInputStream());
		
		String fileName = data_in.readUTF();
		System.out.println("Enviando arquivo: " + fileName);
		
		File file = new File("server/"+fileName);
        FileInputStream in_file = new FileInputStream(file);
		
        data_out.flush();        
        data_out.writeLong(file.length());        
		
        byte[] buffer = new byte[Constant.SIZE_BUFFER_SERVER];    
        int bytes_read = -1;
        
        
        out.flush();        
        while ((bytes_read = in_file.read(buffer, 0, Constant.SIZE_BUFFER_SERVER)) != -1){
        	
        	out.write(buffer, 0, bytes_read);
        	
        	//adicionando informaçoes estatisticas:
        	long rate =  bytes_read / (System.currentTimeMillis() - timeStarted +1);
        	rates.addRate(rate);
        	timeStarted = System.currentTimeMillis();
        	
        }
        in_file.close();        
        System.out.println("Arquivo " + fileName + ", Enviado.");
        
        System.out.println("Arquivo: " + fileName + " Recebido com exito[ media: " + rates.avg + "]");
	}
	
	private void start() throws IOException {		
		sendControlMessenger(Control.RECEIVED);
		sendFile();
		sendControlMessenger(Control.SUCCESS);
	}

	@Override
	public void execute() {
		try {
			start();
		} catch (IOException e) {
			try {
				sendControlMessenger(Control.FAIL);				
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			try {
				getSocket().close();
			} catch (IOException e) {				
				e.printStackTrace();
			}
		}
	}
}
